'use strict'

import { app, protocol, BrowserWindow, ipcMain, Tray, Menu } from 'electron'
import {
  createProtocol
  /* installVueDevtools */
} from 'vue-cli-plugin-electron-builder/lib'
const { autoUpdater } = require('electron-updater')
const isDevelopment = process.env.NODE_ENV !== 'production'

const winURL = process.env.NODE_ENV === 'development'
  ? 'http://localhost:8080'
  : `file://${__dirname}/index.html`
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
let tray
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true } }])

function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({
    width: 400,
    height: 550,
    frame: false,
    webPreferences: {
      nodeIntegration: true
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL(winURL)
  }

  win.on('closed', () => {
    win = null
  })
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow()
  }
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
  }
  // 创建渲染窗口
  createWindow()
  // 设置托盘
  tray = new Tray('resources/ico/icon.png')
  // 设置托盘菜单
  const trayContextMenu = Menu.buildFromTemplate([
    {
      label: '打开',
      click: () => {
        win.show()
      }
    }, {
      label: '退出',
      click: () => {
        app.quit()
      }
    }
  ])

  tray.setToolTip('myApp')
  tray.on('click', () => {
    win.show()
  })
  tray.on('right-click', () => {
    tray.popUpContextMenu(trayContextMenu)
  })
})

app.setAppUserModelId('我的程序')

ipcMain.on('changWindowSize', e =>
  win.setSize(1050, 700)
)

ipcMain.on('close', e =>
  win.hide()
)

ipcMain.on('minimize', e =>
  win.minimize()
)

// 定义calendar窗体
let calendarWin
// 创建calendar窗口方法
function openCalendarWindow () {
  calendarWin = new BrowserWindow({
    width: 400,
    height: 550,
    parent: win, // win是主窗口
    webPreferences: {
      nodeIntegration: true
    }
  })
  // calendarWin.loadURL(winURL + '#/Calendar')
  calendarWin.loadURL('http://127.0.0.1/index.html')
  calendarWin.on('closed', () => { calendarWin = null })
}
ipcMain.on('openCalendarWindow', e =>
  openCalendarWindow()
)
ipcMain.on('checkForUpdate', e =>
  updateHandle()
)

// 检测更新，在你想要检查更新的时候执行，renderer事件触发后的操作自行编写
function updateHandle () {
  autoUpdater.checkForUpdates()
  const message = {
    error: '检查更新出错',
    checking: '正在检查更新……',
    updateAva: '检测到新版本，正在下载……',
    updateNotAva: '现在使用的就是最新版本，不用更新'
  }
  autoUpdater.setFeedURL('http://127.0.0.1/exe')
  // eslint-disable-next-line handle-callback-err
  autoUpdater.on('error', function (error) {
    sendUpdateError(JSON.stringify(error))
    sendUpdateMessage(message.error)
  })
  autoUpdater.on('checking-for-update', function () {
    sendUpdateMessage(message.checking)
  })
  autoUpdater.on('update-available', function (info) {
    console.log(info)
    sendUpdateMessage(message.updateAva)
  })
  autoUpdater.on('update-not-available', function (info) {
    console.log(info)
    sendUpdateMessage(message.updateNotAva)
  })

  // 更新下载进度事件
  autoUpdater.on('download-progress', function (progressObj) {
    console.log(progressObj.percent)
    win.webContents.send('downloadProgress', progressObj)
  })
  autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
    ipcMain.on('isUpdateNow', (e, arg) => {
      console.log(arg)
      console.log('开始更新')
      // some code here to handle event
      autoUpdater.quitAndInstall()
    })

    win.webContents.send('isUpdateNow')
  })
}

// 通过main进程发送事件给renderer进程，提示更新信息
function sendUpdateMessage (text) {
  win.webContents.send('message', text)
}
function sendUpdateError (text) {
  win.webContents.send('error', text)
}
// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', data => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
